package com.example.file_demo.util;

import org.springframework.web.multipart.MultipartFile;
import java.io.*;

public class FileToMultipartFile implements MultipartFile {
    private final byte[] content;
    private final String name;

    public FileToMultipartFile(File file) throws IOException {
        this.name = file.getName();
        this.content = readFileToByteArray(file);
    }

    private byte[] readFileToByteArray(File file) throws IOException {
        try (InputStream input = new FileInputStream(file);
             ByteArrayOutputStream output = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[1024];
            int length;
            while ((length = input.read(buffer)) != -1) {
                output.write(buffer, 0, length);
            }
            return output.toByteArray();
        }
    }

    @Override
    public String getName() {
        return name;
    }

    @Override
    public String getOriginalFilename() {
        return name;
    }

    @Override
    public String getContentType() {
        return "application/octet-stream";  // 根据需要返回正确的MIME类型
    }

    @Override
    public boolean isEmpty() {
        return content.length == 0;
    }

    @Override
    public long getSize() {
        return content.length;
    }

    @Override
    public byte[] getBytes() {
        return content;
    }

    @Override
    public InputStream getInputStream() {
        return new ByteArrayInputStream(content);
    }

    @Override
    public void transferTo(File dest) throws IOException, IllegalStateException {
        try (OutputStream output = new FileOutputStream(dest)) {
            output.write(content);
        }
    }
}